﻿#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include "GreedyWall.h"
#include "GreedySnake.h"
#include "GreedyFood.h"
#include <ctime>
#include <conio.h>
#include <Windows.h>

void gotoxy(HANDLE hOut, int x, int y)
{
	COORD pos;
	pos.X = x;             //横坐标
	pos.Y = y;            //纵坐标
	SetConsoleCursorPosition(hOut, pos);
}
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);//定义显示器句柄变量

//main341：贪食蛇游戏
int main341()
{
	//2.添加随机数种子；
	srand((unsigned int)time(NULL));

	//5.是否死亡标识；
	bool isDead = false;

	char preKey = NULL;

	GreedyWall wall;
	wall.initWall();
	wall.drawWall();

	/*
	//1.测试；
	wall.setWall(5, 4, '=');
	wall.setWall(5, 5, '=');
	wall.setWall(5, 6, '@');
	wall.drawWall();

	cout << wall.getWall(0, 0) << endl;//*
	cout << wall.getWall(5, 4) << endl;//=
	cout << wall.getWall(5, 6) << endl;//@
	cout << wall.getWall(1, 1) << endl;//
	*/

	GreedyFood food(wall);
	food.setFood();

	//GreedySnake snake(wall);
	GreedySnake snake(wall, food);
	snake.initSnake();

	/*GreedyFood food(wall);
	food.setFood();*/

	//snake.delPoint();

	/*snake.move('w');
	snake.move('w');
	snake.move('a');*/

	//wall.drawWall();
	gotoxy(hOut, 0, GreedyWall::ROW);
	cout << "游戏得分：" << snake.getScore() << "分！" << endl;

	//gotoxy(hOut, 10, 5);//y*2 x

	//3.接收用户输入；
	//while (true)
	while (!isDead)
	{
		char key = _getch();

		//7.判断，如果是第一次按了左键，就不能激活游戏；判断，上一次的移动方向；
		if (preKey == NULL && key == snake.LEFT)
		{
			continue;
		}

		do
		{
			if (key == snake.UP || key == snake.DOWN || key == snake.LEFT || key == snake.RIGHT)
			{
				//9.判断本次按键，是否与上次冲突；
				if ((key == snake.LEFT && preKey == snake.RIGHT) ||
					(key == snake.RIGHT && preKey == snake.LEFT) ||
					(key == snake.UP && preKey == snake.DOWN) ||
					(key == snake.DOWN && preKey == snake.UP)
					)
				{
					key = preKey;
				}
				else
				{
					//10.不是冲突按键，可以重新按键；
					preKey = key;
				}

				if (snake.move(key) == true)
				{
					//4.移动成功，代码；
					/*system("cls");
					wall.drawWall();*/
					gotoxy(hOut, 0, GreedyWall::ROW);

					cout << "游戏得分：" << snake.getScore() << "分！" << endl;
					//Sleep(300);
					Sleep(snake.getSleepTime());
				}
				else
				{
					isDead = true;
					break;
				}
			}
			else
			{
				//8.强制将错误按键变为，上一次移动的方向；
				key = preKey;
			}

			//6._kbhit()，当没有键盘输入的时候，返回0；
		} while (!_kbhit());
	}

	system("pause");
	return EXIT_SUCCESS;
}